package org.abyss.upload.resolver;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import edu.tgc.entity.file.FilePath;

public class LocalFileUploadResolver implements UploadResolver {

    @Override
    public boolean delete(String fileName, FilePath path) throws IOException {
        File source = new File(path.getPath(), fileName);
        if (source.exists()) {
            return source.delete();
        }
        return false;
    }

    @Override
    public byte[] read(String fileName, FilePath path) throws IOException {
        File source = new File(path.getPath(), fileName);
        if (source.exists()) {
            return FileCopyUtils.copyToByteArray(source);
        }
        return null;
    }

    @Override
    public void write(MultipartFile source, String fileName, FilePath path) throws IOException {
        File serverPath = new File(path.getPath());
        if (!serverPath.exists()) {
            serverPath.mkdirs();
        }
        String name = fileName == null ? UUID.randomUUID().toString() : fileName;
        File target = new File(serverPath, name);
        source.transferTo(target);
    }
}
